package com.lagou.edu.utils;

import com.lagou.edu.mapper.MapperService;
import com.lagou.edu.request.RequestProcessor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author 赵虎
 * @date 2020/11/16 15:57
 */
public class ExecutorProcessor  extends Thread {

    private MapperService mapperService;

    public ExecutorProcessor(MapperService mapperService) {
        this.mapperService = mapperService;
    }

    @Override
    public void run() {
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        try {
            ServerSocket serverSocket = new ServerSocket(mapperService.getPort());
            System.out.println("=====>>>Minicat start on port：" + mapperService.getPort());
            while (true) {
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket, mapperService.getMapperEngine());
                threadPoolExecutor.execute(requestProcessor);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
